# -*- coding: utf-8 -*-
import logging

from common import orm
from common.campaign.model.moist import MoistCampaign
from common.account.model.account import Account
from common.coupon.db import award_coupon_in_transaction
from common.utils.decorator import sql_wrapper


_LOGGER = logging.getLogger('campaign')


@sql_wrapper
def check_in(user_id, recharge_price, award_price, coupons):
    item = MoistCampaign.query.filter(
        MoistCampaign.user_id == user_id).with_lockmode('update').first()
    if not item:
        item = MoistCampaign()
        item.user_id = user_id
        item.recharge_price = recharge_price
        item.award_price = award_price
        item.save(auto_commit=False)
        for coupon in coupons:
            coupon_tid, start_ts = coupon['tid'], coupon['start_ts']
            award_coupon_in_transaction(user_id, coupon_tid, start_ts=start_ts, coupon_from=u'首充福利')
        orm.session.commit()
        _LOGGER.info('%s check in moist campaign succ. recharge %s',
                     user_id, recharge_price)
        return True
    return False

@sql_wrapper
def get_status(user_id):
    item = MoistCampaign.query.filter(
        MoistCampaign.user_id == user_id).first()
    return item
